import React, { useState, useRef, useContext, createContext } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Button
} from "@mui/material";

// Create Context
const ConfirmContext = createContext();

export const useConfirm = () => useContext(ConfirmContext);

export const ConfirmServiceProvider = ({ children }) => {
    const [options, setOptions] = useState(null);
    const awaitingPromiseRef = useRef(null);

    const openModal = options => {
        setOptions(options);
        return new Promise((resolve, reject) => {
            awaitingPromiseRef.current = { resolve, reject };
        });
    };

    const handleClose = () => {
        if (awaitingPromiseRef.current) {
            awaitingPromiseRef.current.reject();
        }
        setOptions(null);
    };

    const handleConfirm = () => {
        if (awaitingPromiseRef.current) {
            awaitingPromiseRef.current.resolve();
        }
        setOptions(null);
    };

    return (
        <>
            <ConfirmContext.Provider value={openModal} children={children} />
            <Dialog
                open={Boolean(options)}
                sx={{
                    transition: 'all .2s ease-in-out',
                    '& .MuiPaper-root': {
                        marginTop: '-18rem',
                        width: '24rem',
                    }
                }}
            >
                <DialogTitle sx={{ fontSize: '1rem' }}>
                    确定操作
                </DialogTitle>
                <DialogContent>
                    <DialogContentText>{options && options.title ? options.title : ""}?</DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button color="primary" onClick={handleClose} autoFocus>
                        取消
                    </Button>
                    <Button color="primary" onClick={handleConfirm}>
                        确定
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    );
};
